<template>
    <mavon-editor
            ref="mavonEditor"
            v-model="editorValue"
            @change="mavonChange"
            @imgAdd="imgAdd"
            @imgDel="imgDel"
    >
        <!-- 左工具栏后加入自定义按钮  -->
        <template slot="left-toolbar-after">
            <button
                    type="button"
                    @click="selectImgByServer('test')"
                    class="op-icon fa fa-mavon-align-left"
                    aria-hidden="true"
                    title="选择网络图片，插入到编辑器"
            ></button>
        </template>
    </mavon-editor>
</template>
<script>
import {uploadSingle} from "@/plugins/request";
import {Message} from "element-ui";
import turnDownService from "@/plugins/turnDownService";

let baseURL;

process.env.NODE_ENV === "production"
    ? (baseURL = process.env.VUE_APP_PROD_API)
    : process.env.VUE_APP_DEV_API;

export default {
    name: "Editor",
    components: {},
    data() {
        return {
            editorValue: null,
            editorDom: null,
        };
    },
    mounted() {
        //这里负责将html类型的字符串转为md，并存到this.editorValue
        let goods = this.$route.params.row
        let dom = goods ? goods.content : "";
        //用来搞markdown语法的
        this.editorValue = turnDownService.turndown(dom);
    },
    methods: {
        selectImgByServer(a) {
            Message.info("会在这里实现一个网络图片浏览器,方便您手动插入图");
        },

        mavonChange(a, b, c) {
            //内容发生改变就会触发
            //a markdown语法的字符串 b html语法的字符串(重要，微信小程序的rich text需要它)
            // 每次修改都将修改的值放到dom中，点击提交按钮时会被handleGoods组件拿走
            this.editorDom = b;
        },
        async imgAdd(pos, file) {
            //上传图片时如果没有同在一行会解析失败
            try {
                let formdata = new FormData();
                formdata.append("image", file);
                let {status, message, data} = await uploadSingle(formdata);
                debugger;
                if (status !== 200) {
                    return Message.error(message);
                }

                await this.$refs.mavonEditor.$img2Url(
                    pos,
                    data.url.replaceAll("\\", "/")
                );
            } catch (e) {
                Message.error("上传图片发生了错误:" + e.message);
            }
        },
        async imgDel(a, b, c) {
            console.log(a, b, c);
        },
    },
};
</script>
